<template>
  <a-drawer
    :width="340"
    :mask-closable="false"
    :visible="dataModel.visible"
    unmount-on-close
    :ok-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel">
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-form
        ref="authorityDrawerForm"
        layout="vertical"
        :model="formData"
        :disabled="dataModel.disabled"
        :style="{width:'100%'}">
        <a-form-item
          field="title"
          label="资源名称"
          :rules="[{required: true, message:'请输入资源名称'}]">
          <a-input v-model="formData.title" placeholder="请输入资源名称..." allow-clear />
        </a-form-item>
        <a-form-item
          field="name"
          label="资源编码"
          :rules="[{required: true, message:'请输入资源编码'}]">
          <a-input v-model="formData.name" placeholder="请输入资源编码..." allow-clear />
        </a-form-item>
        <a-form-item
          field="type"
          label="资源类型"
          :rules="[{required: true, message:'请选择资源类型'}]">
          <a-radio-group v-model="formData.type" type="button">
            <a-radio :value="0">菜单</a-radio>
            <a-radio :value="1">权限</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="!formData.type"
          field="path"
          label="路由">
          <a-input v-model="formData.path" placeholder="请输入路由地址..." allow-clear />
        </a-form-item>
        <a-form-item
          v-if="!formData.type"
          field="component"
          label="组件路径">
          <a-select v-model="formData.component" placeholder="请输入组件路径..." allow-create allow-clear>
            <a-option value="/layout/default-layout.vue">/layout/default-layout.vue</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-if="!formData.type"
          field="redirect"
          label="重定向">
          <a-input v-model="formData.redirect" placeholder="请输入重定向地址..." allow-clear />
        </a-form-item>
        <a-form-item
          field="order"
          label="排序">
          <a-input-number v-model="formData.order" placeholder="请输入排序..." allow-clear />
        </a-form-item>
        <a-form-item
          v-if="!formData.type"
          field="icon"
          label="图标">
          <a-input v-model="formData.icon" placeholder="请输入图标..." allow-clear />
        </a-form-item>
        <a-form-item v-if="!formData.type" field="enabled" label="缓存">
          <a-switch
            v-model:model-value="formData.cache"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              开启
            </template>
            <template #unchecked>
              关闭
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item v-if="!formData.type" field="enabled" label="标签页">
          <a-switch
            v-model:model-value="formData.affix"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              开启
            </template>
            <template #unchecked>
              关闭
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item v-if="!formData.type" field="enabled" label="隐藏左侧菜单">
          <a-switch
            v-model:model-value="formData.hidden"
            type="round"
            :checked-value="true"
            :unchecked-value="false"
            unchecked-color="#F53F3F"
          >
            <template #checked>
              是
            </template>
            <template #unchecked>
              否
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item
          field="parentId"
          label="上级项">
          <a-tree-select
            v-model="formData.parentId"
            :allow-clear="true"
            :data="authorities"
            :field-names="{
                key: 'id'
            }"
            tree-check-strictly
            placeholder="请选择上级资源..."
          ></a-tree-select>

        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Message } from "@arco-design/web-vue";
import useDataModel from "@/hooks/data-model";
import useLoading from "@/hooks/loading";
import { ValidatedError } from "@arco-design/web-vue/es/form/interface";
import { create, findById, treeList, update } from "@/api/modules/system/authority";
import { disableNode } from "@/utils/tree-utils";
import type { AuthorityDto, AuthorityVo } from "@/types/modules/system";
import { Operation } from "@/types/global";

const defaultFormData = () => ({
  id: 0,
  title: '',
  name: '',
  path: '',
  component: '',
  type: 1,
  parentId: 0,
  order: 10,
  cache: true,
  affix: true,
  hidden: false
});

const authorityDrawerForm = ref<any>()
const authorities = ref<AuthorityVo[]>()
const formData = ref<AuthorityDto>(defaultFormData());
const { dataModel, openModel, closeModel } = useDataModel();
const { loading, setLoading } = useLoading();
const emit = defineEmits(["refresh"]);

const createHandle = async () => {
  openModel("添加资源信息", false, true, Operation.CREATE);
  authorities.value = [{id: 0, title: '无上级项', meta: {}}, ...((await treeList()).data  || [])]
};

const updateHandle = async (id: number) => {
  authorities.value = [{id: 0, title: '无上级项', meta: {}}, ...((await treeList()).data  || [])]
    const { data: authorityVo } = await findById(id)
  disableNode(id, authorities.value)
  const { name, title, parentId, order, component, type, path, redirect } = authorityVo
  formData.value = {
      id, name, title, parentId, order, component, type, path, redirect,
      ...authorityVo.meta
  }
  openModel("编辑资源信息", false, true, Operation.UPDATE);
}

const previewHandle = async (id: number) => {
  authorities.value = [{id: 0, title: '无上级项', meta: {}}, ...((await treeList()).data || [])]
  const { data: authorityVo } = await findById(id)
  if (!authorityVo) {
    Message.error({
      content: "数据不存在",
      duration: 2000
    });
  }
  const { name, title, parentId, order, component, type, path, redirect } = authorityVo
  formData.value = {
    id, name, title, parentId, order, component, type, path, redirect,
    ...authorityVo.meta
  }
  openModel("预览资源信息", true, false, Operation.PREVIEW);
}

const handleCancel = () => {
  closeModel();
  formData.value = defaultFormData()
  setLoading(false);
};

const handleOk = async () => {
  if (dataModel.submit) {
    setLoading(true);
    if (authorityDrawerForm.value) {
      authorityDrawerForm.value?.validate(async (errors: undefined | Record<string, ValidatedError>) => {
        if(!errors) {
          try {
            if (dataModel.type === Operation.CREATE) {
              await create(formData.value);
              Message.success({
                content: "添加成功",
                duration: 2000
              });
            } else {
              await update(formData.value);
              Message.success({
                content: "修改成功",
                duration: 2000
              });
            }
          } finally {
            handleCancel();
          }
          emit("refresh");
        } else {
          setTimeout(() => {
            setLoading(false);
          }, 1000);
        }
      });
    }
  }
}

defineExpose({ createHandle, updateHandle, previewHandle });
</script>

<script lang="ts">
export default {
  name: 'AuthorityDrawer'
}
</script>

<style scoped>

</style>
